package com.boot.cluster.worker.bean;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jgroups.Address;
import org.jgroups.stack.IpAddress;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Data
public class Node implements Serializable {
    private static final long serialVersionUID = 2158634022311343385L;
    //主机名称
    private String name;

    private String ip;
    private int port;

    public Node() {

    }

    public Node(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public static List<Address> to(List<Node> list) {
        try {
            return list.stream().map(s -> s.to()).collect(Collectors.toList());
        } catch (Exception ex) {
            log.error("转换主机IP异常", ex);
            return null;
        }
    }


    public Address to() {
        try {
            return new IpAddress(this.ip, this.port);
        } catch (Exception ex) {
            log.error("获取主机IP异常,{}", ip, ex);
            return null;
        }
    }

    public Node from(IpAddress address) {
        // address.getIpAddress().getHostName()
        return new Node(address.getIpAddress().getHostAddress(), address.getPort());
    }

}
